const koa = require('koa')
const router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const mysql = require('mysql')
const app = new koa()
const route = new router()
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : '1707b',
    password : '123456',
    database : '1707b' // 数据库的名字
  })

connection.connect()


route.post('/api/login', async(ctx, next) => {
    try {
        // 取到传来的数据
        const { name, password } = ctx.request.body
        console.log(name, password)
        // 用户表里面有相应的账号和密码
        const result = await new Promise((resolve, reject) => {
            connection.query(`select * from user where name="${name}" and password="${password}"`, function(err, result) {
                if (err) {
                    console.log(err)
                    reject(err)
                }

                resolve(result)
            })
        })
        if (result.length === 1) {
            ctx.response.body = {
                code: 1,
                msg: '登录成功'
            }
        } else {
            ctx.response.body = {
                code: 0,
                msg: '登录失败'
            }
        }
    } catch(e) {
        ctx.response.body = {
            code: 0,
            msg: e.message
        }
    }
})

route.get('/api/list', async(ctx, next) => {
    try{
        const arr = await new Promise((resolve, reject) => {
            connection.query('select * from user', function(err, results) {
                if (err) reject(err.message)
                resolve(results)
            })
        })
        ctx.response.body = {
            code:1,
            data: arr
        }
    }catch(e) {
        ctx.response.body = {
            code:0,
            msg: e
        }
    }
})

route.post('/api/delete/member', async(ctx, next) => {
    try{
        const { id } = ctx.request.body
        const arr = await new Promise((resolve, reject) => {
            connection.query('delete from user where id=?', id, function(e, result){
                if (e) reject(e)
                resolve(result)
            })
        })
        ctx.response.body = {
            code: 1,
            msg: '删除成功'
        }
    }catch(e) {
        ctx.response.body = {
            code: 0,
            msg: e.message
        }
    }
})



app.use(bodyParser()).use(route.routes()).use(route.allowedMethods())
app.listen(3000)